//
//  UpListVC.m
//  运营管理系统
//
//  Created by 杨毅 on 17/1/3.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "UpListVC.h"

@interface UpListVC ()
{
    NSDictionary *_parameter;
    NSMutableArray *_dataSoure;
    NSMutableArray *_dataSource1;
    //NSMutableArray *_StationDataSource;
    UIButton *_btn;
    BOOL isSelected;
    NSString *_alertTitle;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property(nonatomic,strong)AFHTTPSessionManager *manager;
@property(nonatomic,strong)UITableView *tableview;

@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UIView *backView;
@property (nonatomic,strong)XJhisPsonCell *cell;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
@property (nonatomic,strong)ZJAlertListView *alertList;
@property (nonatomic,strong)NSMutableArray *StationDataSource;
@end

@implementation UpListVC
- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"故障提交";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    _parameter = @{userid:[NSString stringWithFormat:@"%ld",dele.userId]};
    _dataSoure = [[NSMutableArray alloc]init];
    _dataSource1 = [[NSMutableArray alloc]init];
    _StationDataSource = [[NSMutableArray alloc]init];
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableview.backgroundColor = [UIColor clearColor];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableview];
    
    [_tableview registerNib:[UINib nibWithNibName:@"XJhisPsonCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self networking];
}
- (void)networking{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:XJhistoryURL parameters:_parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        XJBranchDataModel *DataModel = [[XJBranchDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (XJBranchListModel *model in DataModel.beanList) {
            model.expand = NO;
            [_dataSoure addObject:model];
        }
        _btn.selected = NO;
        if (_dataSoure.count == 0) {
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"暂时没有数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }
        [self.tableview reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:
     ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD hideHUDForView:self.view animated:YES];
         if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
             _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
             _Fallview.delegate = self;
             [self.view addSubview:_Fallview];
         }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"未能连接到服务器。"]){
             _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
             _ServerFView.delegate = self;
             [self.view addSubview:_ServerFView];
         }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
             _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
             _JoinFalutView.delegate = self;
             [self.view addSubview:_JoinFalutView];
         }else{
             
         } 
     }];
}
- (void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self networking];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self networking];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self networking];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self networking];
}
#pragma mark-->tableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataSoure.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    XJBranchListModel *model = _dataSoure[section];
    if (_btn.selected == NO) {
        return 0;
    }else{
        return model.beanList.count;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.headerView = [[UIView alloc]init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.headerView.frame = CGRectMake(0, 0,self.view.frame.size.width ,40);
    UIImageView *leftImageV = [[UIImageView alloc]initWithFrame:CGRectMake(5, 2, 35, 35)];
    leftImageV.image = [UIImage imageNamed:@"conp_icon"];
    [self.headerView addSubview:leftImageV];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectZero];
    XJBranchListModel *model = _dataSoure[section];
    
    title.text = model.branchName;
    title.font = [UIFont systemFontOfSize:15.0];
    title.textColor = UIColorFromRGB(0x4d4d4d);
    title.numberOfLines = 0;
    [self.headerView addSubview:title];
    
    CGRect rect = [title.text boundingRectWithSize:CGSizeMake(kSCREEN_WIDTH-60, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:title.font,NSFontAttributeName, nil] context:nil];
    CGFloat height = rect.size.height;
    
    
    title.frame = CGRectMake(50, 13, kSCREEN_WIDTH-60, height);
    _btn = [UIButton buttonWithType:UIButtonTypeCustom];
    _btn.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 44);
    [_btn setBackgroundImage:[[UIImage imageNamed:@""]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    //a_bottom a_top
    [_btn setBackgroundImage:[[UIImage imageNamed:@""]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];
    _btn.tag = section;
    [_btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    _btn.selected = !isSelected;
    [self.headerView addSubview:_btn];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 43, kSCREEN_WIDTH, 1)];
    line.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [self.headerView addSubview:line];
    return self.headerView;
}
- (void)close:(UIButton *)sender{
    
    
    isSelected = sender.isSelected;
    
    if (sender.selected == NO)
    {
        
        //将当前状态设置为normal
        
        [_dataSoure removeAllObjects];
        [self networking];
        
        
        
    }else{
        
        XJBranchListModel *lModel = _dataSoure[sender.tag];
        UIApplication *app = [UIApplication sharedApplication];
        AppDelegate *dele = app.delegate;
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
        NSDictionary *parame = @{userid:[NSString stringWithFormat:@"%ld",dele.userId],@"branchId":[NSString stringWithFormat:@"%ld",lModel.branchId]};
        //  NSSLog(@"%@",parame);
        [_manager POST:XJhisPsonURL parameters:parame progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            XJhisPsonDataModel *dataModel = [[XJhisPsonDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
            
            XJBranchListModel *model1 = _dataSoure[sender.tag];
            
            NSArray <XJhisPsonListModel> *arr = dataModel.beanList;
            
            model1.beanList = arr;
            
            sender.selected = YES;
            
            [self.tableview reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            NSInteger status = responses.statusCode;
            //        NSSLog(@"%ld",(long)responses.statusCode);
            if (status >=500 || status == 0) {
                [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
            }else{
                [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
            }
        
        }];
    }
    
    /*
     //记得刷新表格,这样_expand的改变才会生效
     //刷新指定段
     NSIndexSet *index = [NSIndexSet indexSetWithIndex:sender.tag];
     [_tableview reloadSections:index withRowAnimation:UITableViewRowAnimationFade];
     
     */
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!_cell) {
        _cell = [[XJhisPsonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    XJBranchListModel *model = _dataSoure[indexPath.section];
    NSArray *arr = model.beanList;
    XJhisPsonListModel *psonModel = arr[indexPath.row];
    [_cell fillCellWithModel:psonModel];
    return _cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XJBranchListModel *model = _dataSoure[indexPath.section];
    NSArray *arr = model.beanList;
    _alertTitle = model.branchName;
    XJhisPsonListModel *psonModel = arr[indexPath.row];
    [self StationLoad:psonModel.userId];
    
}
//站点数据网络请求
- (void)StationLoad:(NSInteger)userID{
    [_StationDataSource removeAllObjects];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:XJhisStationURL parameters:@{@"userId":[NSString stringWithFormat:@"%ld",userID]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        XJhisStationDataModel *dataModel = [[XJhisStationDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (XJhisStationListModel *model in dataModel.beanList) {
            
            [_StationDataSource addObject:model];
        }
        if (_StationDataSource.count != 0) {

            _alertList = [[ZJAlertListView alloc] initWithFrame:CGRectMake(20, 64, kSCREEN_WIDTH-20, kSCREEN_HEIGHT-90)];
            _alertList.datasource = self;
            _alertList.delegate = self;
            _alertList.titleLabel.text = _alertTitle;
            //点击确定的时候，调用它去做点事情
            //__weak weakSelf = self;
            __weak __typeof__(self) weakSelf = self;
            [_alertList setDoneButtonWithBlock:^{
                
                NSIndexPath *selectedIndexPath = weakSelf.selectedIndexPath;

                XJhisStationListModel *model = weakSelf.StationDataSource[selectedIndexPath.row];

                GZupdataViewController *upVC = [[GZupdataViewController alloc]init];
                upVC.userId = userID;
                upVC.stationId = model.stationId;
                upVC.stationN = model.stationName;
                
                [weakSelf.navigationController pushViewController:upVC animated:YES];
                
            }];
            //选择列表消失是 清空数据 如果不设置当前函数只会选择列表消失 不会清空数据
            [_alertList setCancelButtonBlock:^{
                [weakSelf.StationDataSource removeAllObjects];
            }];
            [_alertList show];

        }else{
            [self showAlert:@"温馨提示" message:@"当前选中人员没有站点" actionWithTitle:@"确定"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500 || status == 0) {
            [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }

    }];
    
}


//站点列表
#pragma mark -设置行数
- (NSInteger)alertListTableView:(ZJAlertListView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _StationDataSource.count;
}

- (UITableViewCell *)alertListTableView:(ZJAlertListView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableAlertListCellWithIdentifier:identifier];
    if (nil == cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if ( self.selectedIndexPath && NSOrderedSame == [self.selectedIndexPath compare:indexPath])
    {
        cell.imageView.image = [UIImage imageNamed:@"dx_checkbox_red_on.jpg"];
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"dx_checkbox_off"];
    }
    XJhisStationListModel *model = _StationDataSource[indexPath.row];
    cell.textLabel.text = model.stationName;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:15.0];
    cell.textLabel.textColor = UIColorFromRGB(0x4d4d4d);
    return cell;
}

- (void)alertListTableView:(ZJAlertListView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView alertListCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"dx_checkbox_off"];
    
}

- (void)alertListTableView:(ZJAlertListView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    UITableViewCell *cell = [tableView alertListCellForRowAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"dx_checkbox_red_on.jpg"];
    
}
- (void)dismissAlert{
    
    [_StationDataSource removeAllObjects];
    [_alertList dismiss];
}
//视图消失时 销毁站点view 同时销毁站点数据
- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    [_StationDataSource removeAllObjects];
    [_alertList dismiss];
}



#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
